package com.gogowan.agroenterprise.newview;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.RetrofitUtil.GsonUtil;
import com.gogowan.agroenterprise.model.BoxCode;
import com.gogowan.agroenterprise.model.CheckCodeRequest;
import com.gogowan.agroenterprise.model.InKickMendRequest;
import com.gogowan.agroenterprise.model.IntStorageBoxResult;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.NewBoxCode;
import com.gogowan.agroenterprise.model.NewOutStorageBoxResult;
import com.gogowan.agroenterprise.model.OutBackRequest;
import com.gogowan.agroenterprise.model.OutCheckRequest;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.adapter.Base_Adapater;
import com.gogowan.agroenterprise.widget.adapter.MyBaseAdapater;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class TakeStorageActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.out_storage_fh_btn)
    ImageButton outStorageFhBtn;

    @BindView(R.id.out_storage_smhqdh_btn)
    ImageView outStorageSmhqdhBtn;
    @BindView(R.id.out_storage_ckmc_text)
    TextView outStorageCkmcText;
    @BindView(R.id.out_storage_jxs_spinner)
    Spinner outStorageJxsSpinner;
    @BindView(R.id.xssj)
    Button xssj;
    @BindView(R.id.out_storage_smrkxm_btn)
    Button outStorageSmrkxmBtn;
    @BindView(R.id.out_storage_smrkxm_btn_hw)
    Button outStorageSmrkxmBtnHw;
    @BindView(R.id.out_storage_xmlist)
    ListView outStorageXmlist;
    @BindView(R.id.out_storage_qrck_btn)
    Button outStorageQrckBtn;

    private TextView outStorageDhEdit;
    private RadioButton TcRb,BfRb;
    private boolean IsModify=true;
    private String OldeOrderCode="";
    private ProgressDialog progressDialog;
    private List<BoxCode> BoxInfo =new ArrayList<>();
    private Base_Adapater adapater;
    
    private int Type=1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.new_activity_out_storage_take);
        ButterKnife.bind(this);
        InitValue();
        TextView title=(TextView)findViewById(R.id.out_activity_title_tv);
        title.setText("入库踢除");
        findViewById(R.id.out_storage_fh_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        adapater=new Base_Adapater(this,BoxInfo);
        adapater.setOnItemListener(new Base_Adapater.OnItemListener() {
            @Override
            public String ItemStr(int position) {
                return  "码号 :"+BoxInfo.get(position).getBackEwm()+
                        "\n产品名称 :"+BoxInfo.get(position).getMaterialName()+
                        "\n产品规格 :"+BoxInfo.get(position).getMaterialSpecication()+
                        "\n产品数量 :"+BoxInfo.get(position).getMaCount()+
                        "\n垛 数 量 :"+BoxInfo.get(position).getDuoCount()+
                        "\n箱    数 :"+BoxInfo.get(position).getBoxCount()+
                        "\n礼盒数量 :"+BoxInfo.get(position).getGiftCount();
            }
        });
        adapater.setRightView(true,"删除");
        adapater.setListener(new MyBaseAdapater.onItemViewClickListener() {
            @Override
            public void onItemViewpositioni(int position) {
                showWindow(position);
            }
        });
        TcRb=(RadioButton)findViewById(R.id.tcrb);
        BfRb=(RadioButton)findViewById(R.id.bfrb);
        TcRb.setOnClickListener(this);
        BfRb.setOnClickListener(this);
        TcRb.performClick();
        outStorageXmlist.setAdapter(adapater);
        outStorageDhEdit=(TextView)findViewById(R.id.out_storage_dh_edit);
        outStorageDhEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final EditText editText=new EditText(TakeStorageActivity.this);
                new AlertDialog.Builder(TakeStorageActivity.this)
                        .setTitle("请输入单号")
                        .setView(editText)
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                EditOrder(editText.getText().toString());
                                BoxInfo.clear();
                                adapater.notifyDataSetChanged();
                            }
                        })
                        .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .show();
            }
        });
        outStorageSmhqdhBtn.setOnClickListener(this);
        outStorageSmrkxmBtn.setOnClickListener(this);
        outStorageSmrkxmBtnHw.setVisibility(View.GONE);
        outStorageQrckBtn.setOnClickListener(this);
    }

    private void EditOrder(final String codeStr) {
        if (OldeOrderCode.length()>0&&(!OldeOrderCode.equals(codeStr))){
            new AlertDialog.Builder(TakeStorageActivity.this)
                    .setTitle("提示")
                    .setMessage("更换单号将会清除已扫数据，您是否要更换单号")
                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            outStorageDhEdit.setText(codeStr);
                            BoxInfo.clear();
                            adapater.notifyDataSetChanged();
                        }
                    })
                    .setNeutralButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    })
                    .show();
        }else {
            outStorageDhEdit.setText(codeStr);
        }
    }

    private void ErrorClick() {
        showToast("类型已锁定，无法更换！");
        switch (Type){
            case 1:
                TcRb.performClick();
                break;
            case 2:
                BfRb.performClick();
                break;
        }
    }

    private void showWindow(final int position) {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("您是否要删除此条数据")
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        BoxInfo.remove(position);
                        adapater.notifyDataSetChanged();
                        if (BoxInfo.size()<1){
                            IsModify=true;
                        }
                    }
                })
                .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
    }

    private void InitValue() {
        SharedPreferences preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
        
        
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
            case R.id.out_storage_smhqdh_btn:
                // 扫码获取单号
                intent = new Intent(Intents.Scan.ACTION);
                this.startActivityForResult(intent, 10);
                break;
            case R.id.out_storage_smrkxm_btn:
                // 扫描入库箱码
//                intent = new Intent(Intents.Scan.ACTION);
//                intent.putExtra(Intents.Scan.IS_BULT_MODE, true);
//                this.startActivityForResult(intent, 20);
                intent = new Intent(Intents.Scan.ACTION);
                this.startActivityForResult(intent, 20);
                break;
            case R.id.out_storage_smrkxm_btn_hw:
                intent = new Intent(TakeStorageActivity.this, HWDialogActivity.class);
                intent.putExtra("type", "lx");
                this.startActivityForResult(intent, 505);
                break;
            case R.id.tcrb:
                if (IsModify){
                    Type=1;
                }else {
                    ErrorClick();
                }
                break;
            case R.id.bfrb:
                if (IsModify){
                    Type=2;
                }else {
                    ErrorClick();
                }
                break;
            case R.id.out_storage_qrck_btn:

                SaveHttp();
                break;
        }
    }

    private void SaveHttp() {
        if (outStorageDhEdit.getText().toString().length()<1){
            showToast("请扫描单号！");
            return;
        }
        if (BoxInfo.size()<1){
            showToast("请扫码!");
            return;
        }
        progressDialog = ProgressDialog.show(this,
                getString(R.string.alert_title),
                "正在提交...", true, false);
        InKickMendRequest inKickMendRequest=new InKickMendRequest();
        inKickMendRequest.setBoxCode(BoxInfo);
       // inKickMendRequest.setEnterpriseId(loginResultInfo.getEnterpriseinfo().getEnterpriseid());
        inKickMendRequest.setOrder(outStorageDhEdit.getText().toString());
        inKickMendRequest.setUserId(MyApplication.mSettings.getLong("personid",0));
        inKickMendRequest.setType(Type);
        inKickMendRequest.setUserType(MyApplication.mSettings.getInt("usertype",0));
        Http(inKickMendRequest, "46000", progressDialog, new RetrofitHttpListener() {
            @Override
            public void OnJson(String str) {
                ResultInfo resultInfo=GsonUtil.GsonToBean(str,ResultInfo.class);
                if (resultInfo.getResult()>0){
                    showToast(resultInfo.getResultinfo());
                    finish();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            final String codeStr;
            switch (requestCode) {
                case 10:
                    // 扫码获取单号
                    codeStr = data.getStringExtra(Intents.Scan.RESULT);
                    EditOrder(codeStr);
                    break;
                case 20:
                case 505:
                    // 扫描入库箱码
                    String s =   data.getStringExtra(Intents.Scan.RESULT);
                    s = s.substring(s.indexOf("=") + 1, s.length());

                    if (Utils.isEmpty(s)) {
                        showToast("扫码失败!");
                        return;
                    }
                    QueryHttp(s);
                    break;
                default:
                    break;
            }
        }
    }

    private void QueryHttp(String code) {
        IsModify=false;
        String OrderCode=outStorageDhEdit.getText().toString();
        if (Utils.isEmpty(OrderCode)){
            showToast("请扫描单号");
            return;
        }else {
            if (Utils.isEmpty(OrderCode)){
                OldeOrderCode=OrderCode;
            }
        }
        progressDialog = ProgressDialog.show(this,
                getString(R.string.alert_title),
                getString(R.string.alert_message), true, false);
        CheckCodeRequest checkCodeRequest=new CheckCodeRequest();
        checkCodeRequest.setCode(code);
        checkCodeRequest.setStoreNo(OrderCode);
        checkCodeRequest.setType(Type);
        //checkCodeRequest.setEnterpriseID(loginResultInfo.getEnterpriseinfo().getEnterpriseid());
        checkCodeRequest.setUserType(MyApplication.mSettings.getInt("usertype",0));
        Http(checkCodeRequest, "45000", progressDialog, new RetrofitHttpListener() {
            @Override
            public void OnJson(String str) {
                IntStorageBoxResult intStorageBoxResult= GsonUtil.GsonToBean(str,IntStorageBoxResult  .class);
                showToast(intStorageBoxResult.getResultinfo());
                if (intStorageBoxResult!=null){
                    if (intStorageBoxResult.getResult()>0){
                        BoxInfo.addAll(intStorageBoxResult.getBoxInfo());
                        adapater.notifyDataSetChanged();
                    }else {
                        showToast(intStorageBoxResult.getResultinfo());
                    }
                }else {
                    showToast("数据解析失败！");
                }
            }
        });
    }
}
